package com.ls.fw.open.manager;

import java.io.IOException;
import java.util.Properties;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import com.ls.fw.commons.core.utils.string.StringUtils;
import com.ls.fw.commons.open.AppSecretManager;
import com.ls.fw.commons.open.OpenException;

public class FileAppSecretManager implements AppSecretManager {

    
	/**
	 * @Fields ROLE : TODO(用一句话描述这个变量表示什么)
	 */
	
	private static final String ROLE = "#role#";

	private String appSecretFile = "config/fw/appSecret.properties";

    private Properties properties;

    public String getSecret(String appId) {
        String string = get(appId);
        String secret = "";
        if(StringUtils.isNotBlank(string)){
          String[] strs = string.split(ROLE);
          secret = strs[0];
        }
        return secret;
    }

	
	/**
	 * 
	 * @author lisheng
	 * @date 2016年6月11日 下午12:34:02
	 * @version V1.0
	 * @param appId
	 * @return
	 */
	private String get(String appId) {
		if (properties == null) {
            try {
                DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
                Resource resource = resourceLoader.getResource(appSecretFile);
                properties =   PropertiesLoaderUtils.loadProperties(resource);
            } catch (IOException e) {
                throw new OpenException("在类路径下找不到appSecret.properties的应用密钥的属性文件");
            }
        }
		String string = null;
		if(appId!=null){
			string = properties.getProperty(appId);
		}
		return string;
	}

    public void setAppSecretFile(String appSecretFile) {
        this.appSecretFile = appSecretFile;
    }

    @Override
    public boolean isValidAppId(String appId) {
    	if(appId == null){
    		return false;
    	}
        return getSecret(appId) != null;
    }

	@Override
	public String[] getRoles(String appId) {
		String string = get(appId);
        String[] roles = null;
        if(StringUtils.isNotBlank(string)){
          String[] strs = string.split(ROLE);
          if(strs.length>1){
        	  roles = strs[1].split(",");
          }
        }
		return roles;
	}
}

